﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	public class SelEditPipe : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Selection selection = activeUIDocument.Selection;
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(2);
			if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			try
			{
				for (;;)
				{
					if (selection.GetElementIds().Count > 0)
					{
						List<Pipe> list = new List<Pipe>();
						foreach (ElementId elementId in selection.GetElementIds())
						{
							Element elementById = activeUIDocument.Document.GetElementById(elementId);
							if (elementById is Pipe)
							{
								list.Add(elementById as Pipe);
							}
						}
						if (list.Count > 0)
						{
							if (new PipeFrm(commandData, list).ShowDialog() == DialogResult.Cancel)
							{
								break;
							}
						}
						else
						{
							RevitVersionFuncs.ClearSelection(selection);
						}
					}
					if (selection.GetElementIds().Count <= 0)
					{
						List<Pipe> list2 = new List<Pipe>();
						PipeFilter pipeFilter = new PipeFilter();
						IList<Element> list3 = selection.PickElementsByRectangle(pipeFilter, "请框选要查询、修改的水管：");
						if (list3 == null || list3.Count < 1)
						{
							YJKMessageBox.Show("没有选中任何水管，请重新选择！");
							continue;
						}
						List<Element> list4 = new List<Element>();
						foreach (Element element in list3)
						{
							if (element is Pipe)
							{
								list2.Add(element as Pipe);
								list4.Add(element);
							}
						}
						RevitVersionFuncs.SetSelection(selection, list4);
						if (list2.Count > 0 && new PipeFrm(commandData, list2).ShowDialog() == DialogResult.Cancel)
						{
							break;
						}
					}
					RevitVersionFuncs.ClearSelection(selection);
				}
			}
			catch (Exception)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
